package com.liu.utils;

import com.alibaba.druid.pool.DataSourceClosedException;
import com.alibaba.druid.pool.DruidDataSource;
import com.liu.model.Student;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;





//泛型类，T：虚拟类型
public class DBRsHelp<T> {
    public List<T> util(T t,ResultSet resultSet) throws SQLException, IllegalAccessException, InstantiationException {
        //需要返回的对象集合
        List<T> classes = new ArrayList<>();

        //循环获取每个resultSet对象
        while (resultSet.next()){
            T c = (T) t.getClass().newInstance();
            //对象的属性名集合
            Field[] declaredFields =c.getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                //暴力破解private
                declaredField.setAccessible(true);
                /* 根据属性设置值 */
                switch (declaredField.getType().getSimpleName()){
                   case "int":
                       declaredField.set(c,resultSet.getInt(declaredField.getName()));
                       break;
                   case "String":
                       declaredField.set(c,resultSet.getString(declaredField.getName()));
                       break;
                   case "long":
                       declaredField.set(c,resultSet.getLong(declaredField.getName()));
                       break;
               }
            }
            classes.add(c);
        }
        return classes;
    }


    /* 不使用连接池 */
    public static void main(String[] args) throws Exception {
        DBRsHelp<Student> util = new DBRsHelp<Student>();
        Student u = new Student();
        String sql = "select * from stu";

        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?userUnicode=true&characterEncoding=utf8&userSSL=true","root","1234");
        //创建一个 Statement对象，用于将SQL语句发送到数据库。
        Statement statement = connection.createStatement();
        //Statement:用于执行静态SQL语句并返回其生成的结果的对象。
        ResultSet resultSet = statement.executeQuery(sql);

       /* 循环打印name 因为next()是指向下一个，
       所以循环结束后则resultSet中的指针就指空了 下面的转换则不能成功*/
       /*while (resultSet.next()){
            System.out.println(resultSet.getString("name"));
        }*/

        List<Student> util1 = util.util(u, resultSet);
        for (Student users : util1) {
            System.out.println(users);
        }
        connection.close();
        statement.close();
        resultSet.close();
    }
}